﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.UI;
using System.Net;
using System.IO;
using System.Xml;

namespace DevSky.WebParts.YouTube
{
    public class YouTubeVideoToolPart : ToolPart
    {
        #region CONTROLS
        private Panel mainContainer = null;
        private TextBox txtVideoLink = null;
        private TextBox txtPersonalChannel = null;
        private TextBox txtVideoWidth = null;
        private TextBox txtVideoHeight = null;
        private DropDownList ddVideoList = null;
        private DropDownList ddDimension = null;
        private CheckBox chkShowVideoSelection = null;
        private CheckBox chkUsingIFrameEmbedding = null;
        private CheckBox chkUsingSSL = null;
        private CheckBox chkShowSimilarVideos = null;
        private Button btnReloadChannel = null;
        private UpdatePanel ajaxPanel = null;
        private UpdateProgress ajaxProgress = null;
        private CheckBox chkAllowFullScreen = null;
        private Image imgProgress = null;
        private CheckBox chkShowOnlySpecificVideos = null;
        #endregion

        public YouTubeVideoToolPart(string title)
        {
            Title = title;            
        }

        protected override void OnInit(EventArgs e)
        {
            mainContainer = new Panel() { ID = "MainContainer" };
            ddVideoList = new DropDownList() { ID = "ddVideoList", AutoPostBack = true, Width=220 };
            ddVideoList.SelectedIndexChanged += new EventHandler(ddVideoList_SelectedIndexChanged);
            txtVideoLink = new TextBox() { ID = "txtVideoLink", Width=350 };
            
            txtPersonalChannel = new TextBox() { ID = "txtPersonalChannel", AutoPostBack= true, Width=350 };
            txtPersonalChannel.TextChanged += new EventHandler(txtPersonalChannel_TextChanged);
            
            chkShowVideoSelection = new CheckBox() { ID = "chkShowVideoSelection", Text="Show video channel list:" };
            chkAllowFullScreen = new CheckBox() { ID = "allowFullScreen", Text="Allow full screen mode" };
            txtVideoWidth = new TextBox() { ID = "txtVideoWidth" };
            txtVideoHeight = new TextBox() { ID = "txtVideoHeight" };
            ddDimension = new DropDownList() { ID = "ddDimension", AutoPostBack=true };
            ddDimension.Items.Add(new ListItem("User defined", string.Empty));
            ddDimension.SelectedIndexChanged += new EventHandler(ddDimension_SelectedIndexChanged);
            ddDimension.Items.Add(new ListItem("420 x 315", "420x315"));
            ddDimension.Items.Add(new ListItem("480 x 360", "480x360"));
            ddDimension.Items.Add(new ListItem("640 x 480", "640x480"));
            ddDimension.Items.Add(new ListItem("960 x 720", "960x720"));
            chkUsingSSL = new CheckBox() { ID = "chkUsingSSL", Text="Use SSL to load videos" };
            chkShowSimilarVideos = new CheckBox() { ID = "chkShowSimilarVideos", Text = "Show similar videos" };
            chkUsingIFrameEmbedding = new CheckBox() { ID = "chkUsingIFrameEmbedding", Text="Use new IFrame embedding option" };

            chkShowOnlySpecificVideos = new CheckBox() { ID = "chkShowOnlySpecificVideos", Text="Show only specified videos" };
            
            btnReloadChannel = new Button() { Text = "Load channel", ID = "btnReloadChannel" };
            btnReloadChannel.Click += new EventHandler(btnReloadChannel_Click);
            
            ajaxPanel = new UpdatePanel() { ID = "ajaxPanelToolPart" };
            ajaxProgress = new UpdateProgress();
            imgProgress = new Image() { ID = "imgProgress", ImageUrl="/_layouts/images/PROGRESS.gif"};


            SetStoredValues();
            base.OnInit(e);
        }

        private void LoadVideoForChannel(string channelName)
        {
            ddVideoList.Items.Clear();
            List<SingleVideo> channelVideos = YouTubeManager.GetVideoForChannel(channelName);
            foreach (SingleVideo video in channelVideos)
                ddVideoList.Items.Add(new ListItem(video.Title, video.ID));
        }

        protected override void CreateChildControls()
        {
            HtmlTable layout = new HtmlTable();            
            layout.Rows.Add(CreatePropertyEntry(txtPersonalChannel, "YouTube Channel name:"));
            Panel panel = new Panel();
            panel.Controls.Add(ddVideoList);
            panel.Controls.Add(btnReloadChannel);
            layout.Rows.Add(CreatePropertyEntry(panel, "Videos in channel:"));
            if (IsYouTubeCarousel)
            {
                layout.Rows.Add(CreateInlinePropertyEntry(chkShowOnlySpecificVideos, ""));
            }
            layout.Rows.Add(CreatePropertyEntry(txtVideoLink, "Video short link(s)"));
            layout.Rows.Add(CreatePropertyEntry(ddDimension, "Predefined dimensions:"));
            layout.Rows.Add(CreatePropertyEntry(txtVideoWidth, "Video width:"));
            layout.Rows.Add(CreatePropertyEntry(txtVideoHeight, "Video height:"));
            layout.Rows.Add(CreateInlinePropertyEntry(chkShowVideoSelection, ""));
            layout.Rows.Add(CreateInlinePropertyEntry(chkUsingIFrameEmbedding, ""));
            layout.Rows.Add(CreateInlinePropertyEntry(chkUsingSSL, "")); 
            layout.Rows.Add(CreateInlinePropertyEntry(chkShowSimilarVideos, ""));
            layout.Rows.Add(CreateInlinePropertyEntry(chkAllowFullScreen, ""));
            #region Progress template
            ajaxProgress.Controls.Add(imgProgress);
            ajaxProgress.Controls.Add(new Label() { Text = "Working ..." });
            ajaxPanel.ContentTemplateContainer.Controls.Add(ajaxProgress);
            #endregion
            ajaxPanel.ContentTemplateContainer.Controls.Add(layout);

            Controls.Add(ajaxPanel);
            base.CreateChildControls();
        }

        #region EVENTS
        void ddDimension_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(ddDimension.SelectedValue))
            {
                string[] values = ddDimension.SelectedValue.Split(new char[] { 'x' });
                txtVideoWidth.Text = values[0];
                txtVideoHeight.Text = values[1];
            }
            else
            {
                txtVideoWidth.Text = string.Empty;
                txtVideoHeight.Text = string.Empty;
            }
        }

        void btnReloadChannel_Click(object sender, EventArgs e)
        {
            LoadVideoForChannel(txtPersonalChannel.Text);
        }

        void ddVideoList_SelectedIndexChanged(object sender, EventArgs e)
        {
            string videoID = ddVideoList.SelectedItem.Value;
            videoID = videoID.Substring(videoID.LastIndexOf('/') + 1);
            if (IsYouTubeCarousel)
            {
                if (!string.IsNullOrEmpty(txtVideoLink.Text))
                    txtVideoLink.Text += ";";
                txtVideoLink.Text += videoID;
            }
            else
                txtVideoLink.Text = videoID;
        }

        void txtPersonalChannel_TextChanged(object sender, EventArgs e)
        {
            LoadVideoForChannel(txtPersonalChannel.Text);
        }
        #endregion

        #region APPLY CHANGES
        public override void ApplyChanges()
        {
            base.ApplyChanges();
            IYouTubeToolpartSettings parent = ParentToolPane.SelectedWebPart as IYouTubeToolpartSettings;
            if (parent != null)
            {
                parent.VideoLink = txtVideoLink.Text;
                parent.ChannelName = txtPersonalChannel.Text;
                parent.ChannelVideoLink = ddVideoList.SelectedValue;
                parent.ShowVideoSelection = chkShowVideoSelection.Checked;
                parent.VideoHeight = txtVideoHeight.Text;
                parent.VideoWidth = txtVideoWidth.Text;
                parent.IFrameEmbedding = chkUsingIFrameEmbedding.Checked;
                parent.UseSSL = chkUsingSSL.Checked;
                parent.ShowSimilarVideos = chkShowSimilarVideos.Checked;
                parent.AllowFullScreen = chkAllowFullScreen.Checked;
                parent.ShowOnlySpecifiedVideos = chkShowOnlySpecificVideos.Checked;
            }
        }

        private void SetStoredValues()
        {
            IYouTubeToolpartSettings parent = ParentToolPane.SelectedWebPart as IYouTubeToolpartSettings;
            if (parent != null)
            {
                txtVideoLink.Text = parent.VideoLink;
                txtPersonalChannel.Text = parent.ChannelName;
                ddVideoList.SelectedValue = parent.ChannelVideoLink;
                chkShowVideoSelection.Checked = parent.ShowVideoSelection;
                txtVideoHeight.Text = parent.VideoHeight;
                txtVideoWidth.Text = parent.VideoWidth;
                chkUsingIFrameEmbedding.Checked = parent.IFrameEmbedding;                
                ListItem item = ddDimension.Items.FindByValue(string.Format("{0}x{1}", txtVideoWidth.Text, txtVideoWidth.Text));
                if (item != null)
                    ddDimension.SelectedValue = item.Value;
                chkUsingSSL.Checked = parent.UseSSL;
                chkShowSimilarVideos.Checked = parent.ShowSimilarVideos;
                chkAllowFullScreen.Checked = parent.AllowFullScreen;
                chkShowOnlySpecificVideos.Checked = parent.ShowOnlySpecifiedVideos;
            }
        }
        
        #endregion

        #region HELPER

        private bool IsYouTubeCarousel
        {
            get
            {
                return (ParentToolPane.SelectedWebPart is YouTubeCarousel);
            }
        }

        private HtmlTableRow CreatePropertyEntry(Control ctl, string description)
        {
            HtmlTableRow row = new HtmlTableRow();
            HtmlTableCell cell = new HtmlTableCell();
            row.Controls.Add(cell);
            HtmlGenericControl div = null;
            if (!string.IsNullOrEmpty(description))
            {
                div = new HtmlGenericControl("DIV");
                div.Attributes.Add("class", "UserSectionHead");
                cell.Controls.Add(div);
                div.Controls.Add(new Label() { Text = description });
            }
            div = new HtmlGenericControl("DIV");
            div.Attributes.Add("class", "UserSectionBody");
            cell.Controls.Add(div);
            HtmlGenericControl control = new HtmlGenericControl("DIV");
            control.Attributes.Add("class", "UserControlGroup");
            control.Controls.Add(ctl);
            div.Controls.Add(control);
            return row;
        }

        private HtmlTableRow CreateInlinePropertyEntry(Control ctl, string description)
        {
            HtmlTableRow row = new HtmlTableRow();
            HtmlTableCell cell = new HtmlTableCell();
            row.Controls.Add(cell);
            HtmlGenericControl div = new HtmlGenericControl("DIV");
            div.Attributes.Add("class", "UserSectionInline");
            cell.Controls.Add(div);
            div.Controls.Add(new Label() { Text = description });
            div.Controls.Add(ctl);
            return row;
        }
        #endregion
    }
}
